package com.my_test.webmagic.es;

import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangyalin@act-telecom.com
 * @since 2019-05-27 14:46
 **/
public class EsTe {
    private static Logger logger = LoggerFactory.getLogger(EsTe.class);

    public static TransportClient getTransportClient() {

        TransportClient transportClient = null;

        try {
            // 配置信息
            Settings esSetting = Settings.builder()
                    .put("cluster.name", "elasticsearch")
//                    .put("client.transport.sniff", true)//增加嗅探机制，找到ES集群
//                    .put("thread_pool.search.size", Integer.parseInt(poolSize))//增加线程池个数，暂时设为5
                    .build();

            transportClient = new PreBuiltTransportClient(esSetting);
            InetSocketTransportAddress inetSocketTransportAddress = new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300);
            transportClient.addTransportAddresses(inetSocketTransportAddress);

        } catch (Exception e) {
            logger.error("elasticsearch TransportClient create error!!!", e);
        }

        return transportClient;
    }

    public static void main(String[] args) {
        TransportClient client = getTransportClient();
        Map<String, Object> map = new HashMap<>();
        map.put("name", "张三");
        map.put("title", "2019");
        map.put("content", "elasticsearch TransportClient create error!");

        IndexResponse indexResponse = client.prepareIndex("blogs", "science", 1 + "").setSource(map).get();
        System.out.println(indexResponse);


    }
}
